package com.qiu.greened.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.request.RequestOptions
import com.qiu.greened.R
import com.qiu.greened.bean.ReplyBean
import com.qiu.greened.network.ServiceCreator
import com.qiu.greened.utils.getTimeFormatText

/**
 * 继承自 PagingDataAdapter
 * COMPARATOR: Paging 3 在内部使用 DiffUtil 来管理数据变化
 */
class ReplyAdapter : PagingDataAdapter<ReplyBean, ReplyAdapter.ViewHolder>(COMPARATOR) {
    object COMPARATOR : DiffUtil.ItemCallback<ReplyBean>() {
        override fun areItemsTheSame(oldItem: ReplyBean, newItem: ReplyBean): Boolean {
            return oldItem.replyId == newItem.replyId
        }

        override fun areContentsTheSame(oldItem: ReplyBean, newItem: ReplyBean): Boolean {
            return oldItem == newItem
        }
    }

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val imgUser: ImageView = view.findViewById(R.id.img_user)
        val textName: TextView = view.findViewById(R.id.text_name)
        val textContext: TextView = view.findViewById(R.id.text_content)
        val textTime: TextView = view.findViewById(R.id.text_time)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ReplyAdapter.ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_repst_list, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ReplyAdapter.ViewHolder, position: Int) {
        val item = getItem(position)
        if (item != null) {
            //赋值
            holder.textName.text = item.nickName
            holder.textContext.text = item.replyContent
            holder.textTime.text = getTimeFormatText(item.createTime)
            Glide.with(holder.itemView.context).load(ServiceCreator.BASE_URL + item.userAvatar)
                .apply(RequestOptions.bitmapTransform(CircleCrop())).into(holder.imgUser)
        }
    }
}